package gold.digger;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC316 {
    public long startExecuteTime = System.currentTimeMillis();


    /*
     * @param 此题目参考了别人代码
     * 这是因为问题情况较为复杂
     * 未来需要再次复习此道题目
     * 此题目也是比较经典，贪心+单调栈，并且处理细节容易搞混
     * @return:
     */
    class Solution {
        public String removeDuplicateLetters(String s) {
            int[] count = new int[128];
            for (int i = 0; i < s.length(); i++) {
                count[(int) s.charAt(i)]++;
            }

            Stack<Character> stack = new Stack<>();
            Set<Character> seen = new HashSet<>();
            for (int i = 0; i < s.length(); i++) {
                char cur = s.charAt(i);
                count[((int) cur)]--;   //每遍历一个，就需要减少后面的统计量 ,注意，此处放在这里非常有必要
                if (seen.contains(cur)) continue;

                while (!stack.isEmpty() && stack.peek() > cur && count[((int) stack.peek())] > 0) {
                    seen.remove(stack.pop());
                }
                stack.push(cur);
                seen.add(cur);
            }

            StringBuilder res = new StringBuilder();
            while (!stack.isEmpty()) res.insert(0, stack.pop());
            return res.toString();
        }
    }

    public void run() {
        Solution solution = new Solution();
        System.out.println(solution.removeDuplicateLetters("cbacdcbc"));
    }

    public static void main(String[] args) throws Exception {
        LC316 an = new LC316();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
